import java.io.*;
import java.util.Scanner;

public class IODeom9 {
    public static void main(String[] args) {
        //1.输入必要信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要搜索的路径：");
        String rootPath = scanner.next();
        System.out.println("输入要搜索的单词：");
        String word = scanner.next();

        File rootfile = new File(rootPath);
        if(!rootfile.isDirectory()){
            System.out.println("路径不对");
            return;
        }

        scanDir(rootfile,word);
    }

    private static void scanDir(File rootFile, String word) {
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }

        for (File f:files) {
            System.out.println("当前遍历到" + f.getAbsolutePath());

            if(f.isFile()){
                //在文件内容搜索

                sarchInFile(f,word);

            }else if(f.isDirectory()) {//如果是目录就继续递归
                scanDir(f,word);
            }
        }
    }

    private static void sarchInFile(File f, String word) {

        //通过这个方法在这个在文件内部进行搜索
        try (InputStream inputStream = new FileInputStream(f)){

            StringBuilder builder = new StringBuilder();
            while(true){
                byte[] buffer = new byte[1024];
                int n = inputStream.read();
                if(n == -1){
                    break;
                }

                //此处只是读出文件的一部分 将所有内容连接到一起
                String s = new String(buffer,0,n);
                builder.append(s);
            }

            //当文件读取完毕，从连接起来的内容 中查询所包含的word
            if (builder.indexOf(word) == -1) {
                return;
            }

            //找到了，打印文件的路径
            System.out.println("找到了" +  word +"存在于" + f.getAbsolutePath());

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
